package cn.xshi.common.base.dynamic;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * @Desc DataSourceAdvice
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Aspect
@Component
@Lazy(false)
@Order(0) //Order设定AOP执行顺序 使之在数据库事务上先执行
public class DataSourceAdvice {

    /**
     * 采用AOP 根据方法开头选择主从库
     * @param joinPoint
     */
    @Before("execution(* cn.xshi.*.service.impl.*.*(..))")
//    @Before("execution(* jehc.cloud.*.dao.*.*(..))")
    public void process(JoinPoint joinPoint) {
        String methodName=joinPoint.getSignature().getName();
        if (methodName.startsWith("get")
                ||methodName.startsWith("count")
                ||methodName.startsWith("find")
                ||methodName.startsWith("list")
                ||methodName.startsWith("query")
                ||methodName.startsWith("load")
                ||methodName.startsWith("select")
                ||methodName.startsWith("check")){
            if(!"dataSourceSlave".equals(DataSourceContextHolder.getDbType())){
                DataSourceContextHolder.setDbType("dataSourceSlave");
            }
        }else {
            //切换dataSourceMaster
            if(!"dataSourceMaster".equals(DataSourceContextHolder.getDbType())){
                DataSourceContextHolder.setDbType("dataSourceMaster");
            }
        }
    }
}
